package controller

import (
	"context"
	"database/sql"
	"fmt"
	"ginfast/configs"
	"ginfast/initialize"
	"ginfast/pkg/ginx"
	"ginfast/pkg/orm"
	"log"
	"runtime"
)

type DbInit struct {
}

// IsInitHandler
func (DbInit) IsInitHandler(c *ginx.Context) {
	c.JSONWriteData(orm.DB() != nil)
}

// getEnvInfo
func (DbInit) EnvInfoHandler(c *ginx.Context) {
	c.JSONWrite(ginx.H{"sysOsName": runtime.GOOS, "goVersion": runtime.Version()})
}

type createParam struct {
	DbCharset    string `json:"dbCharset" binding:"required"`
	DbHost       string `json:"dbHost" binding:"required"`
	DbName       string `json:"dbName" binding:"required"`
	DbPass       string `json:"dbPass" binding:"required"`
	DbPort       uint16 `json:"dbPort" binding:"required"`
	DbUser       string `json:"dbUser" binding:"required"`
	RedisAddress string `json:"redisAddress" binding:"required"`
	RedisDb      int    `json:"redisDb" binding:"required"`
	RedisPort    uint   `json:"redisPort" binding:"required"`
	RedisPass    string `json:"redisPass"`
}

// CreateDb
func (DbInit) CreateDb(c *ginx.Context) {
	var p createParam
	if err := c.MustBind(&p); err != nil {
		return
	}
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/", p.DbUser, p.DbPass, p.DbHost, p.DbPort)
	tdb, err := sql.Open("mysql", dsn)
	if err != nil {
		c.JSONWriteError(err)
		return
	}
	res, err := tdb.ExecContext(context.TODO(), fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s` DEFAULT CHARSET %s COLLATE utf8mb4_general_ci", p.DbName, p.DbCharset))
	if err != nil {
		c.JSONWriteError(err)
		return
	}
	log.Println(res)
	tdb.Close()
	configs.GViper.Set("sql", &initialize.DbOptions{
		Name:    "mysql",
		Address: fmt.Sprintf("%s%s?charset=%s&parseTime=True&loc=Local", dsn, p.DbName, p.DbCharset),
	})
	if err := initialize.Database(); err != nil {
		c.JSONWriteError(err)
		return
	}
	// configs.GViper.Set("redis", redis.Options{
	// 	Address:  fmt.Sprintf("%s:%d", p.RedisAddress, p.RedisPort),
	// 	Password: p.RedisPass,
	// 	DB:       p.RedisDb,
	// })
	configs.GViper.WriteConfig() // 更新配置文件
	c.JSONWriteData(true)
}

func (o DbInit) Routers(r *ginx.RouterGroup) {
	r.GET("/isInit", o.IsInitHandler)
	r.GET("/getEnvInfo", o.EnvInfoHandler)
	r.POST("/createDb", o.CreateDb)
}
